package cc.idoone.spring_boot_hello.shiro;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * 密码加密
 */
public class PasswordHelper {

	private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

	private static String hashAlgorithmName = "MD5"; //默认是MD5加密

	private static int hashIterations = 2; //默认密码迭代两次

	/**
	 * 对用户设置加密钥匙，并对密码进行加密
	 */
	public static void encrypt(UserInfo user) {
		user.setCredentialsSalt(randomNumberGenerator.nextBytes().toHex());

		String newPassword = new SimpleHash(
				hashAlgorithmName,
				user.getPassword(),
				ByteSource.Util.bytes(user.getCredentialsSalt()),
				hashIterations
		).toHex();

		user.setPassword(newPassword);
	}

	/**
	 * 返回加密后的结果
	 */
	public static String encrypt(String password, String salt) {
		String newPassword = new SimpleHash(hashAlgorithmName,
				password,
				ByteSource.Util.bytes(salt),
				hashIterations).toHex();
		return newPassword;
	}
}